#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:41:18
'''
import sys
sys.path.append(".")
import json
import datetime
from sqlalchemy import or_, desc
from db_logic.db_base import Repository
from models.log_models import EntityLog
from Common.Utils import Utils
from db_logic.user import BllUser

#日志信息业务逻辑类
class BllLog(Repository):
    def __init__(self, entityType=EntityLog):
        return super().__init__(entityType)

    #获取系统日志列表
    def getLogList(self, customerId, pageParam, keyWord=''):
        keyWord = '%' + keyWord + '%'
        orm_query = self.findList().filter(
            EntityLog.customer_id == customerId
        ).filter(
            or_(
                EntityLog.operate_user_name.like(keyWord), 
                EntityLog.operate_type.like(keyWord)
            )
        ).order_by(desc(EntityLog.operate_date))
        return self.queryPage(orm_query, pageParam)

    # 插入日志记录函数
    def insert_log_record(self, currentInfo_json, ExecuteResult):
        currentInfo = json.loads(currentInfo_json)
        user_id = currentInfo.get('user_id')
        client_code = currentInfo.get('client_code')
        customer_id = currentInfo.get('customer_id')
        user = BllUser().findEntity(user_id)
        entity_log = EntityLog(log_id=str(Utils.UUID()), customer_id=customer_id, LogType=1, operate_user_id=user_id,
                               operate_account=user.account, operate_user_name=user.real_name,
                               operate_type_code='通信成功', operate_type='通信成功',
                               execute_result="终端{0}：{1}".format(
                                   client_code, ExecuteResult),
                               operate_date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 
                               is_add=1
        )
        self.insert(entity_log)
